<template>
  <div class="dashboard-container" ref="top">
    <el-card class="box-card">
      <div slot="header">
        <span>{{ $route.id?'试题修改':'试题录入' }}</span>
      </div>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="学科：" prop="subjectID">
          <el-select
            v-model="ruleForm.subjectID"
            @change="subjectsChange(ruleForm)"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="item in subjectsList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录：" prop="catalogID">
          <el-select
            v-model="ruleForm.catalogID"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="item in directorysList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业：" prop="enterpriseID">
          <el-select
            v-model="ruleForm.enterpriseID"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="item in companysList"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市：" prop="city">
          <el-select
            v-model="ruleForm.province"
            @change="cityChange"
            placeholder="请选择"
            style="width: 198px; margin-right: 4px"
          >
            <el-option
              v-for="item in provincesList"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
          <el-select
            v-model="ruleForm.city"
            placeholder="请选择"
            style="width: 198px"
          >
            <el-option
              v-for="item in citysList"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方向：" prop="direction">
          <el-select
            v-model="ruleForm.direction"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="item in direction"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型：" prop="questionType">
          <el-radio-group v-model="ruleForm.questionType" @change="typeChange">
            <el-radio label="1">单选</el-radio>
            <el-radio label="2">多选</el-radio>
            <el-radio label="3">简答</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度：" prop="difficulty">
          <el-radio-group v-model="ruleForm.difficulty">
            <el-radio label="1">简单</el-radio>
            <el-radio label="2">一般</el-radio>
            <el-radio label="3">困难</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干：" prop="question" >
          <!-- 使用 v-model 进行双向的数据绑定 -->
          <quill-editor v-model="ruleForm.question" @blur="$refs.ruleForm.validateField('question')" ></quill-editor>
        </el-form-item>
        <el-form-item label="选项：" v-if="this.ruleForm.questionType !== '3'">
          <!-- 单选题选择框 -->
          <el-radio-group
            v-model="str"
            v-if="ruleForm.questionType === '1'"
            @change="answerChange"
          >
            <el-row
              v-for="item in ruleForm.options"
              :key="item.code"
              style="
                position: relative;
                height: 60px;
                padding-top: 12px;
                margin-bottom: 20px;
              "
            >
              <el-radio :label="item.code">{{ item.code + '：' }}</el-radio>
              <el-input
                v-model="item.title"
                inline
                style="width: 240px"
              ></el-input>
              <el-upload
                :disabled="!!item.img"
                class="avatar-uploader"
                action="http://192.168.69.83:3000/upload"
                :show-file-list="false"
                :on-success="(res, file)=>handleAvatarSuccess(res, file,item.code)">
                <!-- <img v-if="item.img" :src="item.img" class="avatar"> -->
                <el-image
                  v-if="item.img"
                  class="avatar"
                  :src="item.img"
                  :preview-src-list="[item.img]">
                </el-image>
                <i v-if="item.img" @click.stop="removeImg(item.code)" class="el-icon-circle-close" style="font-size:16px;position:absolute;top:-8px;right:-8px;cursor:pointer;" ></i>
                <div v-else class="el-upload__text" ><span style="font-size:14px">上传图片</span></div>
              </el-upload>
            </el-row>
          </el-radio-group>
          <!-- 多选题选择框 -->
          <el-checkbox-group
            v-model="arr"
            v-if="ruleForm.questionType === '2'"
            @change="answerChange"
          >
            <el-row
              v-for="item in ruleForm.options"
              :key="item.code"
              style="
                position: relative;
                height: 60px;
                padding-top: 12px;
                margin-bottom: 20px;
              "
            >
              <i v-if="item.img" @click="removeImg(item.code)" class="el-icon-circle-close" style="font-size:16px;position:absolute;top:-8px;right:-110px;z-index:9999;cursor:pointer;" ></i>
              <el-checkbox :label="item.code" name="type">{{
                item.code + '：'
              }}</el-checkbox>
              <el-input
                v-model="item.title"
                inline
                style="width: 240px"
              ></el-input>
              <el-upload
                :disabled="!!item.img"
                class="avatar-uploader"
                :action="'http://192.168.69.83:3000/upload'"
                :show-file-list="false"
                :on-success="(res, file)=>handleAvatarSuccess(res, file,item.code)">
                <el-image
                  v-if="item.img"
                  class="avatar"
                  :src="item.img"
                  :preview-src-list="[item.img]">
                </el-image>
                <i v-if="item.img" @click.stop="removeImg(item.code)" class="el-icon-circle-close" style="font-size:16px;position:absolute;top:-8px;right:-8px;cursor:pointer;" ></i>
                <div v-else class="el-upload__text" ><span style="font-size:14px">上传图片</span></div>
              </el-upload>
            </el-row>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item v-if="this.ruleForm.questionType !== '3'">
          <el-button type="danger" size="small" :disabled="isAdd" @click="addAnswer">+增加选项与答案</el-button>
        </el-form-item>
        <el-form-item label="解析视频：" >
          <el-input v-model="ruleForm.videoURL" style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item label="答案解析：" prop="answer">
          <!-- 使用 v-model 进行双向的数据绑定 -->
          <quill-editor v-model="ruleForm.answer" @blur="$refs.ruleForm.validateField('answer')"></quill-editor>
        </el-form-item>
        <el-form-item label="题目备注：" >
          <el-input
            type="textarea"
            v-model="ruleForm.remarks"
            style="width: 400px"
          ></el-input>
        </el-form-item>
        <el-form-item label="试题标签：" prop="tags">
          <el-select
            v-model="ruleForm.tags"
            multiple
            filterable
            placeholder="请选择面试题标签"
            style="width: 400px"
          >
            <el-option
              v-for="item in tagsList"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >确认提交</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { simple as subjects } from '@/api/hmmm/subjects.js'
import { simple as directorys } from '@/api/hmmm/directorys.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { direction } from '@/api/hmmm/constants'
import { simple as tags } from '@/api/hmmm/tags'
import { list as companys } from '@/api/hmmm/companys'
import { add, detail, update } from '@/api/hmmm/questions'
export default {
  data () {
    return {
      name: 'questions-new',
      subjectsList: [], // 学科的数组
      directorysList: [], // 目录的数组
      provincesList: [], // 城市的数组
      citysList: [], // 地区的数组
      direction, // 方向的数组
      companysList: [], // 企业的数组
      tagsList: [],
      str: '', // 选项
      arr: [], // 多选选项
      ruleForm: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型 1单选2多选3简答
        difficulty: '1', // 难度  1简单2一般3困难
        question: '', // 题干
        options: [
          // 选项
          {
            code: 'A', // 代码  题目选择序号
            title: '', // 标题  先择项
            img: '', // 图片URL
            isRight: false // 是否正确答案
          },
          {
            code: 'B', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false // 是否正确答案
          },
          {
            code: 'C', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false // 是否正确答案
          },
          {
            code: 'D', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false // 是否正确答案
          }
        ],
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签
      },
      rules: {
        subjectID: [{ required: true, message: '选择学科', trigger: 'change' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'change' }],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        city: [{ required: true, message: '请选择城市', trigger: 'change' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'change' }],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'blur' }
        ],
        tags: [{ required: true, message: '请输入标签', trigger: 'blur' }]
      }
    }
  },
  methods: {
    typeChange () {
      // 题型改变的时候 清空选项
      this.str = ''
      this.arr = []
      this.ruleForm.options = [
        // 选项
        {
          code: 'A', // 代码  题目选择序号
          title: '', // 标题  先择项
          img: '', // 图片URL
          isRight: false // 是否正确答案
        },
        {
          code: 'B', // 代码
          title: '', // 标题
          img: '', // 图片URL
          isRight: false // 是否正确答案
        },
        {
          code: 'C', // 代码
          title: '', // 标题
          img: '', // 图片URL
          isRight: false // 是否正确答案
        },
        {
          code: 'D', // 代码
          title: '', // 标题
          img: '', // 图片URL
          isRight: false // 是否正确答案
        }
      ]
    },
    async getCompanys () { // 获得企业列表
      const { data } = await companys()
      // console.log(data)
      this.companysList = data.items
    },
    addAnswer () { // 增加选项与答案
      const obj = {
        code: '',
        title: '',
        img: '',
        isRight: false
      }
      const num =
        this.ruleForm.options[
          this.ruleForm.options.length - 1
        ].code.charCodeAt()
      obj.code = String.fromCharCode(num + 1)
      this.ruleForm.options.push(obj)
    },
    handleAvatarSuccess (res, file, code) { // 上传头像成功的钩子
      this.ruleForm.options.forEach(item => {
        if (item.code === code) {
          item.img = 'http://192.168.69.83:3000/' + res.url
        }
      })
    },
    answerChange (data) {
      this.ruleForm.options.forEach((item) => {
        item.isRight = !!data.includes(item.code)
      })
    },
    cityChange (str) {
      // 城市变化的钩子
      this.citysList = citys(str)
    },
    async subjectsChange (from) {
      // 学科变化时触发的钩子
      this.ruleForm.catalogID = '' // 清空目录表单框
      this.ruleForm.tags = '' // 清空tags框
      this.getDirectorys(from) // 获取目录简单列表
      this.gatTags(from)
    },
    async getSubjects () {
      // 获取学科简单列表
      const { data } = await subjects()
      this.subjectsList = data
    },
    async getDirectorys (from) {
      // 获取目录简单列表
      const { data } = await directorys(from)
      this.directorysList = data
    },
    async gatTags (from) {
      const { data } = await tags(from)
      this.tagsList = data
    },
    submitForm (formName) {
      // 表单提交
      this.$refs[formName].validate(async (valid) => {
        if (!valid) return this.$message.error('请输入必填项')
        this.ruleForm.tags = this.ruleForm.tags.join(',')
        if (this.ruleForm.id) {
          await update(this.ruleForm)
          this.$message.success('题目修改成功')
          this.$router.back(-1) // 路由回退
        } else {
          await add(this.ruleForm)
          this.$message.success('试题录入成功')
          this.$router.push('/questions/list') // 跳转功能
        }
      })
    },
    removeImg (code) { // 图片删除
      this.$confirm('确定取消上传图片么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
        // type: 'warning'
      }).then(() => {
        this.ruleForm.options.forEach(item => {
          if (item.code === code) item.img = ''
        })
      }).catch(_ => _)
    },
    async getDetil () { // 试题修改
      const { data } = await detail({ id: this.$route.query.id })
      this.getDirectorys({ subjectID: data.subjectID }) // 获取目录列表
      this.gatTags({ subjectID: data.subjectID }) // 获取tag列表
      data.tags = data.tags.split(',')
      this.ruleForm = data
      if (data.questionType === '2') {
        data.options.forEach(item => {
          if (item.isRight) {
            this.arr.push(item.code)
          }
        })
      }
      if (data.questionType === '1') {
        data.options.forEach(item => {
          if (item.isRight) {
            this.str = item.code
          }
        })
      }
      this.$nextTick(() => {
        window.scrollTo(0, 0) // 页面滚动到顶部
      })
    }
  },
  created () {
    this.getSubjects() // 获取学科简单列表
    this.provincesList = provinces() // 获取城市列表
    this.getCompanys() // 获得企业列表
    if (this.$route.query.id) {
      this.getDetil()
    }
  },
  computed: {
    isAdd () {
      return this.ruleForm.questionType === '' || this.ruleForm.questionType === '1'
    }
  }
}
</script>

<style scoped lang='scss'>
  .dashboard-container{
    background-color: #fafafa;
    margin: 20px;
  }
  // 设置富文本编辑器的默认最小高度
  ::v-deep .ql-editor {
  min-height: 200px!important;
  }
  ::v-deep .ql-toolbar {
    padding: 0 0 0 8px!important;
  }
  ::v-deep .el-textarea__inner {
    height:96px
  }
  ::v-deep.el-row label.el-radio {
    margin-right: 0;
  }
  ::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    float: left;
    position: absolute;
    top: 0;
    left: 291px;
    // overflow: hidden;
  }
  ::v-deep .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  ::v-deep .el-upload  {
    font-size: 16px;
    width: 100px;
    height: 60px;
    line-height: 60px;
    text-align: center;
  }
  ::v-deep .avatar {
    border-radius: 6px;
    width: 100px;
    height: 60px;
    display: inline-block;
  }
</style>
